package com.youzhi.backend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.youzhi.backend.dto.OperateLogTypeEnum;
import com.youzhi.backend.dto.Page;
import com.youzhi.backend.exception.EcpEnum;
import com.youzhi.backend.exception.YouZhiException;
import com.youzhi.backend.request.PageRequest;
import com.youzhi.backend.service.ICommonService;
import com.youzhi.backend.service.IDoCommonSqlAction;
import com.youzhi.backend.service.IOperateLogService;
import com.youzhi.backend.service.IPagePostPositionProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommonServiceImpl implements ICommonService {


    /**
     * 默认排序字段
     */
    public static String default_order_field = "updateTime";

    public static String order_field_name = "orderField";

    public static String order_field_type = "orderType";

    public static Map<String, String> tableNameAnnotationMap = new HashMap<>();


    static {
        tableNameAnnotationMap.put("user", "用户");
        tableNameAnnotationMap.put("role", "角色");
        tableNameAnnotationMap.put("operateLog", "操作日志");
    }


    /**
     * 获取系统中所有的baseMapper
     * map的k是baseMapper的名称
     */
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private Map<String, IService> serviceMap;


    @Autowired
    private IOperateLogService operateLogService;


    @Override
    public Long count(String tableName, Map<String, Object> params) {
        return (Long) commonSqlTemplateAction(tableName, params,
                (mapper, queryWrapper, queryParams) -> {
                    queryWrapper.allEq(queryParams);
                    return SqlHelper.retCount(mapper.count(queryWrapper));
                });
    }


    @Override
    public IPage<Map<String, Object>> page(String tableName, Map<String, Object> params) {

        IPage<Map<String, Object>> result = (IPage<Map<String, Object>>) commonSqlTemplateAction(tableName, params,
                (serviceImpl, queryWrapper, queryParams) -> {
                    String excludeField = "current,size,orderField,orderType";
                    queryParams.forEach((k, v) -> {
                        if (!excludeField.contains(k)) {
                            queryWrapper.like(k, v);
                        }
                    });

                    IPage page = serviceImpl.page(Page.ofPage(params), queryWrapper);

                    //把对象转城map,为了列表好添加新的字段
                    if (CollUtil.isNotEmpty(page.getRecords())) {
                        List collect = (List) page.getRecords().stream().map(o -> BeanUtil.beanToMap(o)).collect(Collectors.toList());
                        page.setRecords(collect);
                    }

                    return page;
                });

        //添加操作日志
//        operateLogService.addOperateLog(OperateLogTypeEnum.read, "查看" + tableNameAnnotationMap.get(tableName) + "列表", null);
        return result;
    }


    public Map<String, Object> erasureBlankField(Map<String, Object> params) {

        Map<String, Object> queryMap = new HashMap<>();
        params.forEach((k, v) -> {
            //如果前端传的不是空字符串就加入queryMap作为查询条件
            if (!StrUtil.isBlankIfStr(v)) {
                queryMap.put(k, v);
            }
        });

        if (queryMap.isEmpty()) {
            throw YouZhiException.newException(EcpEnum.query_params_is_empty);
        }

        return queryMap;
    }


    public IService getServiceImpl(String tableName) {
        return serviceMap.get(tableName + "ServiceImpl");
    }


    public Object commonSqlTemplateAction(String tableName, Map<String, Object> params, IDoCommonSqlAction action) {

        IService serviceImpl = getServiceImpl(tableName);

        //擦除value = "" | " " 的字段
        Map<String, Object> queryMap = erasureBlankField(params);

        QueryWrapper queryWrapper = new QueryWrapper();

        //添加排序字段
        addOrderField(params, queryWrapper);

        Object result = action.doAction(serviceImpl, queryWrapper, queryMap);

        if (result instanceof IPage &&
                serviceImpl instanceof IPagePostPositionProcessor &&
                CollUtil.isNotEmpty(((IPage) result).getRecords())) {
            result = ((IPagePostPositionProcessor) serviceImpl).process((IPage<Map<String, Object>>) result);
        }

        return result;
    }


    /**
     * 添加排序字段
     */
    private void addOrderField(Map<String, Object> params, QueryWrapper queryWrapper) {
        if (params.containsKey(order_field_name) && params.containsKey(order_field_type)) {
            String orderField = (String) params.get(order_field_name);
            String orderType = (String) params.get(order_field_type);
            if (StrUtil.isNotBlank(orderField) && StrUtil.isNotBlank(orderType)) {
                if ("asc".equals(orderType)) {
                    queryWrapper.orderByAsc(orderField);
                } else {
                    queryWrapper.orderByDesc(orderField);
                }
            }
        } else {
            queryWrapper.orderByDesc(default_order_field);
        }
    }
}
